﻿using Durian.API.Application.Commands.Process;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OfficeOpenXml;

namespace Durian.API.Application.Commands.Assembly
{
    public class ExcelFarrowingsCommandHandler : IRequestHandler<ExcelFarrowingsCommand, FileExportResult>
    {
        private readonly IBaseRepositorys<Assemblies> assembliesRepository;
        private readonly ILogger<ExcelFarrowingsCommandHandler> logger;

        public ExcelFarrowingsCommandHandler(IBaseRepositorys<Assemblies> assembliesRepository, ILogger<ExcelFarrowingsCommandHandler> logger)
        {
            this.assembliesRepository = assembliesRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 导出装配工单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<FileExportResult> Handle(ExcelFarrowingsCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportResult();
            var list = assembliesRepository.GetAll().ToList();
            Console.WriteLine(list.Count);
            var book = new XSSFWorkbook();
            var sheet = book.CreateSheet("装配工单表");

            var row1 = sheet.CreateRow(0);

            //设置表头的各个列标题
            row1.CreateCell(0).SetCellValue("单据编号");
            row1.CreateCell(1).SetCellValue("工单数");
            row1.CreateCell(2).SetCellValue("备注");
            row1.CreateCell(3).SetCellValue("创建时间");

            //初始化索引
            int i = 1;
            foreach (var item in list)
            {
                row1 = sheet.CreateRow(i);

                row1.CreateCell(0).SetCellValue(item.AssemblyNumber);
                row1.CreateCell(1).SetCellValue(item.AssembliesNum);
                row1.CreateCell(2).SetCellValue(item.Remark);
                row1.CreateCell(3).SetCellValue(item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                i++;
            }

            byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }

            string contextType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string fileName = "装配工单导出.xlsx";
            result.FileBytes = bytes;
            result.MimeType = contextType;
            result.FileName = fileName;
            return result;
        }


    }
}
